<#assign hasFile=false/>
<#assign hasImg=false/>
<#assign hasPerSel=false/>
<#list columnList as column>
    <#if column.form>
        <#if column.formType == 'file'>
            <#assign hasFile=true/>
        <#elseif column.formType == 'img'>
            <#assign hasImg=true/>
        <#elseif column.formType == 'orgPer'>
            <#assign hasPerSel=true/>
        <#elseif column.formType == 'project'>
            <#assign hasProSel=true/>
        <#else>
        </#if>
    </#if>
</#list>
<template>
	<!-- ${tableComment}新增/编辑 -->
	<div class="form-content height100">
		<div class="form-content-box">
			<div class="height100">
				<div class="form-content-title clearfix">
					{{
					oprType === "edit"
					? $t("components.uiButton.edit")
					: $t("components.uiButton.add")
					}}{{ menuName }}
					<div class="fr">
						<Icon
								type="md-close"
								size="20"
								class="cursor-pointer"
								@click="closeForm('close')"
						/>
					</div>
				</div>
				<div class="contentCenter scroll-bar con" ref="contentCenter">
					<!-- 提交的表单内容 -->
					<Form
							ref="form"
							:label-width="110"
							:model="formData"
							:rules="formRule"
							label-position="right"
					>
						<Row>
							<div class="form-moudle-title">
								<span class="text">{{ $t("components.uiText.detail") }}</span>
							</div>
						</Row>
						<Row class="list">
                            <#list columnList as column>
                            <#if column.form>
							<#if column.formType == 'org'>
							<Col span="12" v-if="this.userInfo.nodeType == 'ENTERPRISE'">
							<!-- ${column.columnComment} -->
							<FormItem :label="$t('${className}.form.${column.attrName}')" prop="${column.attrName}">
								<OrgTreelist
										@backorgTree="onOrgTreeChanged"
										:selectedDetect="selectedDetect"
								></OrgTreelist>
							</FormItem>
							</Col>
							<Col span="12" v-if="this.userInfo.nodeType == 'PROJECT'">
								<FormItem :label="$t('${className}.form.${column.attrName}')" prop="${column.attrName}">
								<Input
										v-model.trim="userInfo.belongName"
										disabled
								></Input>
							</FormItem>
							</Col>
                            <#elseif column.formType == 'project'>
							<Col span="12">
								<FormItem :label="$t('${className}.form.${column.attrName}')" prop="${column.attrName}">
									<ProjectSelect
											:projectStatus="formData.orgId"
											@backprojectStatus="onProjectSelected"
											:selectedDetect="selectedDetect"
									></ProjectSelect>
								</FormItem>
							</Col>
							<#else>
                            <#if column.formType == 'file'>
							<Col span="24">
                            <#else>
							<Col span="8">
                            </#if>
								<!-- ${column.columnComment} -->
								<FormItem :label="$t('${className}.form.${column.attrName}')" prop="${column.attrName}">
									<#if column.formType == 'text'>
									<Input
											v-model="formData.${column.attrName}"
											type="text"
											maxlength="100"
											clearable
											:disabled="readonly"
											:placeholder="readonly ? '' : $t('${className}.form.placeholder.${column.attrName}')"
									></Input>
									<#elseif column.formType == 'textarea'>
									<Input
											v-model="formData.${column.attrName}"
											type="textarea"
											maxlength="500"
											show-word-limit
											:disabled="readonly"
											:autosize="{ minRows: 5, maxRows: 8 }"
											:placeholder="readonly ? '' : $t('${className}.form.placeholder.${column.attrName}')"
									></Input>
									<#elseif column.formType == 'editor'>
									<!-- 生成暂不支持富文本 -->
									<#elseif column.formType == 'select'>
									<Select
											v-model="formData.${column.attrName}"
											:clearable="true"
											:disabled="readonly"
											:placeholder="readonly ? '' : $t('${className}.form.placeholder.${column.attrName}')"
									>
										<Option
												v-for="item in ${column.attrName?replace("Id", "")}List"
												:value="item.id"
												:key="item.id"
										>{{ item.name }}</Option>
									</Select>
									<#elseif column.formType == 'radio'>
									<RadioGroup
											v-model="formData.${column.attrName}"
											:disabled="readonly">
										<Radio label="1"><span>是</span></Radio>
										<Radio label="2"><span>否</span></Radio>
									</RadioGroup>
									<#elseif column.formType == 'checkbox'>
									<CheckboxGroup
											v-model="formData.${column.attrName}"
											:disabled="readonly">
										<Checkbox label="1"><span>选择1</span></Checkbox>
										<Checkbox label="2"><span>选择2</span></Checkbox>
										<Checkbox label="3"><span>选择3</span></Checkbox>
									</CheckboxGroup>
									<#elseif column.formType == 'date'>
									<DatePicker
											type="date"
											:editable="false"
											:clearable="true"
											format="yyyy-MM-dd"
											:disabled="readonly"
											@on-change="(dateStr) => {formData.${column.attrName} = dateStr;}"
											:value="formData.${column.attrName}"
											:placeholder="readonly ? '' : $t('${className}.form.placeholder.${column.attrName}')"
									>
									</DatePicker>
									<#elseif column.formType == 'datetime'>
									<DatePicker
											type="datetime"
											:editable="false"
											:clearable="true"
											format="yyyy-MM-dd HH:mm"
											:disabled="readonly"
											@on-change="(dateStr) => {formData.${column.attrName} = dateStr;}"
											:value="formData.${column.attrName}"
											:placeholder="readonly ? '' : $t('${className}.form.placeholder.${column.attrName}')"
									>
									</DatePicker>
									<#elseif column.formType == 'file'>
									<FileUpload
											ref="fileUploadRef"
											multiple
											:keyId="'id'"
											:isUpload="!readonly"
											:action="uploadParam.uploadAction"
											:limit="uploadParam.limit"
											:maxSize="uploadParam.maxSize"
											:accept="uploadParam.accept"
											:showLimit="uploadParam.showLimit"
											:uploaded-list="uploadParam.uploadedList"
											:param="uploadParam.bussParam"
											@on-success="onUploadSuccess()"
									>
										<p style="color: rgba(255, 0, 0, 0.85)">
											{{ uploadParam.uploadText }}
										</p>
									</FileUpload>
									<#elseif column.formType == 'image'>
									<ImageUpload
											ref="FileUpload"
											multiple
											:keyId="'id'"
											:isUpload="!readonly"
											:action="uploadParam.uploadAction"
											:limit="uploadParam.limit"
											:maxSize="'10240'"
											:accept="'jpg, jpeg, png'"
											:showLimit="uploadParam.showLimit"
											:uploaded-list="uploadParam.uploadedList"
											:param="uploadParam.bussParam"
											@on-success="onUploadSuccess()"
									>
										<p style="color: rgba(255, 0, 0, 0.85)">
											{{
											"支持格式：jpg、 jpeg、png，等格式文件,单个文件不能超过10MB"
											}}
										</p>
									</ImageUpload>
									<#elseif column.formType == 'orgPer'>
									<Input
											ref="userSelRef"
											v-model="formData.${column.attrName}"
											type="text"
											maxlength="100"
											clearable
											:disabled="readonly"
											:placeholder="readonly ? '' : $t('${className}.form.placeholder.${column.attrName}')"
											@on-focus="onUserSelectedOpen"
									></Input>
									<#else>
									<Input
											v-model="formData.${column.attrName}"
											type="text"
											maxlength="100"
											clearable
											:disabled="readonly"
											:placeholder="readonly ? '' : $t('${className}.form.placeholder.${column.attrName}')"
									></Input>
									</#if>
								</FormItem>
							</Col>
							</#if>
							</#if>
							</#list>
						</Row>
					</Form>
				</div>
			</div>
		</div>
		<div class="panel-footer">
			<Button
					type="primary"
					v-preventReClick="1000"
					:loading="saveLoading"
					@click="handleSubmit"
			>{{ $t("components.uiButton.submit") }}
			</Button>
			<Button
					style="margin-left: 8px"
					icon="ios-undo"
					@click="closeForm('close')"
			>{{ $t("components.uiButton.back") }}
			</Button>
		</div>
        <#if hasPerSel>
		<!-- 企业视角人员选择 -->
		<div v-if="isEnterpriseUser">
			<EnterpriseSelectUser
					:isShow="isEnterpriseUser"
					:chooseType="'person'"
					:isMulti="isMulti"
					:choosedData="currentChooseData"
					:orgObj="getUserParam"
					:type="getUserParam.type"
					@saveModel="onUserSelected"
			></EnterpriseSelectUser>
		</div>
		<!-- 项目视角人员选择 -->
		<div v-if="isProjectUser">
			<ProjectSelectUser
					:isShow="isProjectUser"
					:chooseType="'person'"
					:isMulti="isMulti"
					:choosedData="currentChooseData"
					:orgObj="getUserParam"
					:type="getUserParam.type"
					@saveModel="onUserSelected"
			></ProjectSelectUser>
		</div>
		</#if>
	</div>
</template>
<script>
    <#if hasImg || hasFile>
    import {imgUpload, previewPhoto} from "@/api/common.api";
    </#if>
    <#if hasImg>
    import ImageUpload from "@/components/common/upload/images.vue"; // 文件上传(包含图片)
	</#if>
    <#if hasFile>
    import FileUpload from "@/components/common/upload/file.vue"; // 文件上传(包含图片)
    </#if>
    <#if hasPerSel>
    import EnterpriseSelectUser from "@/components/common/enterpriseSelectUser.vue"; // 企业视角人员上传
    import ProjectSelectUser from "@/components/common/projectSelectUser.vue"; // 项目视角人员上传
	</#if>
	<#if hasPerSel>
    import ProjectSelect from "@/components/common/projectselect.vue";
    </#if>
    import {mapGetters} from "vuex";
    import * as ${className}Api from "@/api/${className}.api";
    import { findNode } from "@/assets/js/util";
    export default {
        name: "${className}Init",
        components: {
            <#if hasImg>
            ImageUpload,
            </#if>
            <#if hasFile>
            FileUpload,
            </#if>
            <#if hasPerSel>
            EnterpriseSelectUser,
            ProjectSelectUser,
            </#if>
            <#if hasPerSel>
            ProjectSelect,
			</#if>
        },
        props: {
            oprType: {
                // 当前是新增/重新发起
                type: String,
                default: "",
            },
            rowInfo: {
                // 编辑列表的行信息
                type: Object,
                default: () => {
                    return {};
                },
            },
        },
        watch: {
            rowInfo: {
                handler: function (nVal) {
                    if (nVal.id) {
                        this.editDataEcho(nVal.id);
                    }
                },
                immediate: true,
                deep: true,
            },
        },
        created() {
            this.setMenuName("${className}"); //根据路由动态获取菜单名称
        },
        data() {
            const readonly = (this.oprType !== 'edit' && this.oprType !== 'add');
            return {
                readonly: readonly,
                projectId: "",
                <#if hasImg || hasFile>
                uploadParam: {
                    bussParam: {
                        source: 0, // 此参数作为业务系统的参数
                        type: 0,
                    },
                    showLimit: 3,
                    uploadAction: imgUpload, // 上传地址
                    delAction: "", // 删除地址
                    uploadText: this.$t("supervisionInspect.warning.checkGist"), // 上传说明
                    maxSize: "20480", // 单个文件的最大限制单位kb doc .docx .pdf.jpg.png
                    limit: "9", // 最多上传个数
                    accept: [
                        "xls",
                        "xlsx",
                        "pdf",
                        "doc",
                        "docx",
                        "zip",
                        "ppt",
                        "pptx",
                        "rar",
                    ], // 支持的文件类型(可在组件中处理为input type="file"的accept类型) accept="image/*,.pdf" ['jpg', 'jpeg', 'png', 'xls', 'xlsx', 'doc', 'docx', 'pdf', 'zip', 'mp4']
                    // accept也可写成字符串 accept: 'jpg, jpeg, png, xls, xlsx, doc, docx, pdf, zip, mp4',
                    uploadedList: [], // 已上传的数据（编辑和详情时回填使用）
                    isUpload: true, // 是否可上传操作 新增和编辑为true，详情为false，false时不显示上传图标和上传说明
                },
				</#if>
                formData: {
                    <#list columnList as column>
                    <#if column.form>
                    ${column.attrName}: "", //${column.columnComment}
					</#if>
					</#list>
                },
                formRule: {
                    <#list columnList as column>
                    <#if column.form && column.required>
                    <#if column.formType == 'select' || column.formType == 'date' || column.formType == 'datetime'>
                    ${column.attrName}: [
                        {required: !readonly, message: this.$t('${className}.form.valid.${column.attrName}'), trigger: "change"},
                    ],
                    <#else>
                    ${column.attrName}: [
                        {required: !readonly, message: this.$t('${className}.form.valid.${column.attrName}'), trigger: "blur"},
                    ],
                    </#if>
                    </#if>
                    </#list>
                },
                saveLoading: false,
                <#if hasPerSel>
                isEnterpriseUser: false, // 是否展示企业视角选人
                isProjectUser: false, // 是否展示项目视角选人
                getUserParam: {},
                currentChooseData: [], // 当前选中的人
                isMulti: false, // 人员选择是否多选
				</#if>
            };
        },
        computed: {
            ...mapGetters(["userInfo"]),
        },
        methods: {
            editDataEcho() {
                // 编辑-获取详情
                this.form = JSON.parse(JSON.stringify(this.form));
                // 其他数据回填转换/处理
                ${className}Api.get${ClassName}Detail(this.form.id).then((res) => {
                    if (res.code == 200) {
                        this.initData(res.data);
                    } else {
                        this.$Message.error(res.msg);
                    }
                });

            },
            <#if hasFile || hasImg>
            onUploadSuccess(ref, fieldKey) {
                this.$refs.contentCenter.scrollTop =
                    this.$refs.contentCenter.scrollHeight;
                setTimeout(() => {
                    let data = this.$refs[ref].getFileList(),
                        fileArr = [];
                    data.forEach((item) => {
                        fileArr.push(item.id);
                    });
                    this.formData[fieldKey] = fileArr.join(",");
                }, 50);
            },
            processFile(formKey){
                // 附件处理
                if (this.formData[formKey]) {
                    let files = this.formData[formKey].split(",");
                    previewPhoto(files).then((res) => {
                        this.uploadParam.uploadedList = res.data.data; //多个文件上传，上传组件和此处的uploadedList需替换成对应的值
                    });
                } else {
                    this.uploadParam.uploadedList = [];
                    this.$set(this.formData, formKey, "");
                }
            },
			</#if>
            <#if hasPerSel>
            //选人组件返回用户信息
            onUserSelectedOpen() {
                this.getUserParam = {
                    ...JSON.parse(JSON.stringify(this.userInfo)),
                    type: 2,
                };
                this.currentChooseData = [{ //xxxxPersonId自行修改
                    personId: this.formData.xxxxPersonId || this.userInfo.personId,
                    personName: this.formData.xxxxPersonName || this.userInfo.personName,
                }];
                this.isMulti = false;
                if (this.userInfo.nodeType === "ENTERPRISE") {
                    this.isEnterpriseUser = true;
                }
                if (this.userInfo.nodeType === "PROJECT") {
                    this.isProjectUser = true;
                }
            },
            onUserSelected(visible, data) {
                this.getUserParam = {};
                // 人员选择数据回填
				if (data) {
					this.personList = JSON.parse(JSON.stringify(data));
					
				} else {
                    //异常处理
                }
				if (this.userInfo.nodeType === "ENTERPRISE") {
					this.isEnterpriseUser = visible;
				}
				if (this.userInfo.nodeType === "PROJECT") {
					this.isProjectUser = visible;
				}
            },
			</#if>
            handleSubmit() {
                this.$refs["form"].validate((valid) => {
                    if (valid) {
                        this.saveLoading = true;
                        let url;
                        if (this.oprType === "add") {
                            url = "${className}Add";
                            this.formData.menuRoute = window.__POWERED_BY_QIANKUN__
                                ? Storage.get("activeAllRoute")
                                : this.$route.name;
                            this.formData.customerId = Storage.get("customerId");
                            this.formData.systemCode = Storage.get("systemCode");
                            this.formData.systemName = decodeURIComponent(
                                Storage.get("systemName")
                            );
                        } else {
                            url = "${className}Edit";
                        }
                        ${className}Api[url](this.formData).then((res) => {
                            if (res.code == 200) {
                                this.$Message.success(res.msg);
                                this.closeForm();
                            } else {
                                this.$Message.error(res.msg);
                            }
                            this.saveLoading = false;
                        })
						.catch(() => {
                            this.saveLoading = false;
                        });

                    }
                });
            },
            closeForm(closeTag) {
                this.$emit("backList", "1", closeTag);
            },
            //动态菜单名称
            setMenuName(menuPath){
                let menuList = JSON.parse(Storage.get('menuList'));
                let path = window.__POWERED_BY_QIANKUN__ ? <#noparse>`${Storage.get("activeAllRoute")}`</#noparse> : menuPath;
                let menu = findNode(menuList, "path", path);
                this.menuName = menu.name || $t("${className}.form.title");
            },
        },
    };
</script>
<style scoped lang="less">
    @import "~@/assets/less/my-theme.less";

    /deep/ input::-webkit-outer-spin-button,
    /deep/ input::-webkit-inner-spin-button {
        -webkit-appearance: none !important;
        margin: 0;
    }

    /deep/ input[type="number"] {
        -moz-appearance: textfield;
    }

    .initiate-info {
        margin-bottom: 18px;
    }

    /deep/ .ivu-btn span:nth-child(1) {
        display: inline;
    }

    .plan-wrap,
    .batch-wrap {
		/deep/ .ivu-input {
			background: unset;
		}
    }
</style>
